package cn.tedu.sp06.filter;

import cn.tedu.sp01.util.JsonResult;
import com.ctc.wstx.util.StringUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class LoginFilter extends ZuulFilter {
    /**
     * 过滤器类型 pre rooting post error
     * @return
     */

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 位置顺序号
     * @return
     */

    @Override
    public int filterOrder() {
        return 6;
    }

    /**
     * 判断针对当前请求 是否执行过滤代码
     * @return
     */
    @Override
    public boolean shouldFilter() {
        //获取当前请求调用的服务Id
        RequestContext ctx = RequestContext.getCurrentContext();
        String serviceId=(String) ctx.get(FilterConstants.SERVICE_ID_KEY);

        //判断id是不是item-service
        return "item-service".equalsIgnoreCase(serviceId);



    }

    /**
     * 过滤代码
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
        //检测token参数

        //得到request 对象
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request=ctx.getRequest();
        // 用request 接受token参数
        request.getParameter("token");
        String token = request.getParameter("token");

        //如果没有token 阻止向后台服务转发 直接向客户端返回响应
        if (StringUtils.isBlank(token)){
            ctx.setSendZuulResponse(false);

            //向客户端直接发送响应
            String json =  JsonResult.err().code(JsonResult.NOT_LOGIN).msg("Not login！ ").toString();
            ctx.addZuulResponseHeader("Content-Type","application/json;charset=utf-8");
            ctx.setResponseBody(json);
        }

        return null;//在当前zuul版本中 没有使用这个返回值
    }
}
